const axios = require('axios')
const crypto = require('crypto')

const accessKeyId = 'LTAIy6iMpNHarJWk'
const appSecret = 'AYxxOPmpvlDxDoUuuY1VcNv7jRnZZv'

let number = 0

function getUrl (resourceUrl) {
  let params = {
    Format: 'JSON',
    Version: '2014-11-11',
    AccessKeyId: accessKeyId,
    SignatureMethod: 'HMAC-SHA1',
    SignatureVersion: '1.0',
    SignatureNonce: Math.round(Math.random() * 10000),
    TimeStamp: (new Date().toISOString()).replace(/\.\d{3}/, ''),
    Action: 'PushObjectCache',
    ObjectPath: resourceUrl,
    ObjectType: 'File',
  }
  params = sortObjectKeys(params)
  let headerString = ''
  Object.keys(params).forEach(key => headerString += `${key}=${encodeURIComponent(params[key])}&`)
  headerString = headerString.slice(0, -1)
  const stringToSign = 'GET&%2F&' + encodeURIComponent(headerString)
  const sign = crypto.createHmac('sha1', appSecret + '&').update(stringToSign).digest('base64')
  return 'https://cdn.aliyuncs.com' + '?' + headerString + '&' + 'Signature=' + encodeURIComponent(sign)
}

function sendRequest (resourceUrl) {

  const url = getUrl(resourceUrl)

  axios.get(url).then(() => {
    console.log(`CDN预热成功：${resourceUrl}`)
  }).catch(({response: {data}}) => {
    if (number > 5) {
      console.log(`CDN预热失败重试次数过多,取消预热`)
    } else {
      number ++
      console.log(`CDN预热失败：${JSON.stringify(data)}`)
      console.log(`再次预热`)
      sendRequest(resourceUrl)
    }
  })
}

function sortObjectKeys(obj) {
  const res = {}
  Object
    .keys(obj || {}).sort((a, b) => { return a < b ? -1 : 1 })
    .forEach(key => { res[key] = obj[key] })
  return res
}

module.exports = sendRequest
